package cn.jisol.ngame.network.websocket;

import cn.jisol.ngame.actions.statesync.SNStateSyncAction;
import cn.jisol.ngame.client.statesync.NStateSyncClient;
import cn.jisol.ngame.proto.message.NGameMessageOuterClass;
import cn.jisol.ngame.util.spring.SpringBeanUtils;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class WebStateSyncSocket {
    
    public static final Map<String, NStateSyncClient> CHATS = new ConcurrentHashMap<>();
    
    SNStateSyncAction SN_StateSync;
    
    @OnOpen
    public void onOpen(Session session){
        
        if (Objects.isNull(SN_StateSync)){
            SN_StateSync = SpringBeanUtils.getBean(SNStateSyncAction.class);
        }
        
        String name = session.getPathParameters().get("name");
        if(Objects.isNull(name)) return;
        
        System.out.println("World2 世界 [" + name + "] 加入世界...");
        
        NStateSyncClient nClient = new NStateSyncClient(session);
        CHATS.put(name,nClient);
        
    }
    
    @OnMessage
    public void onMessage(Session session, NGameMessageOuterClass.NGameMessage message){
        
        String name = session.getPathParameters().get("name");
        if(Objects.isNull(name)) return;
        
        NStateSyncClient nClient = CHATS.get(name);
        if(Objects.nonNull(nClient)) nClient.onMessage(message);
        
    }
    
    
    @OnClose
    public void onClose(Session session){
        
        String name = session.getPathParameters().get("name");
        
        NStateSyncClient client = null;
        if(Objects.nonNull(client = CHATS.get(name)) && Objects.nonNull(client.getRole())){
            
            //如果是房主则移除房主
            switch (client.getRole()){
                case OWNER:
                    SN_StateSync.owner = null;
                    break;
                case PLAYER:
                    SN_StateSync.clients.remove(client.getUuid());
                    break;
            }
            
            
        }
        
        CHATS.remove(name);
        
    }
    
    
}
